<template>
  <div class="chat-container">
    <!-- 聊天内容区域 -->
    <div class="chat-box">
      <div v-for="(message, index) in messages" :key="index" class="message">
        <strong>{{ message.userName }}:</strong> {{ message.content }}
        <small class="timestamp">{{ message.time }}
        <img @click="addThumb(message)" class="thumb" v-if="!message.isThumb" src="@/assets/imgs/thumb.png" alt="">
        <img @click="addThumb(message)" class="thumb" v-if="message.isThumb" src="@/assets/imgs/thumbed.png" alt="">
        {{message.thumbList.length}}</small>
      </div>
    </div>

    <!-- 输入框和发送按钮 -->
    <div class="input-box">
      <input
        v-model="newMessage"
        @keyup.enter="sendMessage"
        placeholder="输入消息..."
        class="message-input"
      />
      <button @click="sendMessage" class="send-button">发送</button>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  data() {
    return {
      newMessage: "", // 用户输入的新消息
      messages: [], // 存储所有聊天消息
      userInfo: {},
      allThumbs: [],
    };
  },
  methods: {
    // 发送消息
    sendMessage() {
      if (this.newMessage.trim() === "") {
        this.$message.error('请输入内容')
        return
      }
      let data = {
        userId: this.userInfo.id,
        content: this.newMessage,
        time: moment().format('yyyy-MM-DD HH:mm:ss')
      }
      this.$request({
        url: '/chat/add',
        method: 'POST',
        data
      }).then(res => {
        if (res.code === '200') {  // 表示成功保存
          this.$message.success('发表成功')
          this.getData()

          // 清空输入框
          this.newMessage = "";

          // 滚动到底部
          this.scrollToBottom();
        } else {
          this.$message.error(res.msg)  // 弹出错误的信息
        }
      })
    },
    // 滚动到聊天底部
    scrollToBottom() {
      this.$nextTick(() => {
        const chatBox = this.$el.querySelector(".chat-box");
        chatBox.scrollTop = chatBox.scrollHeight;
      });
    },
    getData() {
      this.$request({
        url: '/thumb/selectAll',
        method: 'GET',
      }).then(t => {
        this.allThumbs = t.data
        console.log(this.allThumbs)
        this.$request({
          url: '/chat/selectAll',
          method: 'GET',
        }).then(res => {
          this.messages = res.data.map(v2 => {
            return {
              ...v2,
              thumbList: this.allThumbs.filter(v => v.chatId === v2.id),
              isThumb: this.allThumbs.filter(v => v.chatId === v2.id).some(v => v.userId === this.userInfo.id)
            }
          })
          console.log(this.messages)
        })
      })
    },
    addThumb(message) {
      if (message.isThumb) {
        // 删除点赞
        console.log(message)
        let curId = message.thumbList.find(v => v.userId === this.userInfo.id).id
        this.$request({
          url: `/thumb/delete/${curId}`,
          method: 'DELETE'
        }).then(res => {
          this.$message.success('您已取消点赞')
          this.getData()
        })
      } else {
        // 添加点赞
        this.$request({
          url: '/thumb/add',
          method: 'POST',
          data: {
            userId: this.userInfo.id,
            chatId: message.id
          }
        }).then(res => {
          this.$message.success('点赞成功')
          this.getData()
        })
      }
    }
  },
  mounted() {
    // 页面加载时滚动到底部
    this.scrollToBottom();
    this.getData()
    this.userInfo = JSON.parse(localStorage.getItem('xm-user'))
  },
};
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 70vh;
  max-width: 600px;
  margin: 10px auto;
  border: 1px solid #ccc;
  border-radius: 8px;
  overflow: hidden;
}

.chat-box {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message {
  margin-bottom: 10px;
  padding: 8px;
  border-radius: 4px;
  background-color: #e9ecef;
}

.message strong {
  color: #007bff;
}

.timestamp {
  float: right;
  font-size: 12px;
  color: #6c757d;
  display: flex;
  align-items: center;
  gap: 4px;
}

.input-box {
  display: flex;
  padding: 10px;
  border-top: 1px solid #ccc;
  background-color: #fff;
}

.message-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  outline: none;
}

.send-button {
  margin-left: 10px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
}

.send-button:hover {
  background-color: #0056b3;
}
.thumb {
  width: 16px;
  height: px;
  cursor: pointer;
}
</style>